
<div class="layui-card layadmin-header">
  <div class="layui-breadcrumb" lay-filter="breadcrumb">
    <a lay-href="">主页</a>
    <a><cite>商户管理</cite></a>
    <a><cite>所有商户</cite></a>
  </div>
</div>

<div class="layui-fluid">
  <div class="layui-card">
    <div class="layui-tab layui-tab-brief">
      <ul class="layui-tab-title">
        <li class="layui-this">商户列表</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div class="layui-row">
            <div class="layui-form">
              <div class="layui-form-item" style="margin:0;">
                <div class="layui-input-inline">
                  <input type="text" name="mchId" id="mchId" placeholder="商户ID" autocomplete="off" class="layui-input">
                  <input type="text" name="name" id="name" placeholder="商户名称" autocomplete="off" class="layui-input">
                </div>
                <div class="layui-input-inline">
                  <select name="type" id="status" placeholder="商户状态" lay-search="">
                    <option value="-99">所有</option>
                    <option value="1">正常</option>
                    <option value="0">停用</option>
                  </select>
                </div>
                <button id="search" class="layui-btn" data-type="reload">搜索</button>
                <a class="layui-btn" lay-href="merchant/list/mch_add">新增</a>
                <button class="layui-btn layui-btn-normal" id="batchCutOff" >一键日切</button>
              </div>
            </div>
          </div>
          <table id="XxPay_Mgr_Merchant_dataAll" lay-filter="XxPay_Mgr_Merchant_dataAll"></table>
          <div class='layui-row layui-fluid'> 统计： 汇总代付余额 <span style='color:red' id='totalAgnetBalacne' ></span> 元。</div>
        </div>

      </div>
    </div>
  </div>
</div>

<form class="layui-form"  id="cutofftbl" style="display:none">
  <div class="layui-form-item">
    <label class="layui-form-label">一键操作</label>
    <div class="layui-input-inline" >
      <input type="radio" name="cutoffStatus" title="开启" value="1" />
      <input type="radio" name="cutoffStatus" title="关闭" value="0" />
    </div>
  </div>
</form>

<div class="layui-tab-content" id="duijie" style="display: none">
  <form class="layui-form center" lay-filter="duijieDivForm">
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">商户后台:</label>
      <div class="layui-input-block">
        <input name="merchantUrl" id="merchantUrl"  class="layui-input" value="http://150.109.63.144:3502/mch/start/index.html"  style="border: none">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">登录账户:</label>
      <div class="layui-input-block">
        <input type="text" required id="loginAccount" name="loginAccount"  class="layui-input" style="border: none">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">初始密码:</label>
      <div class="layui-input-block">
        <input type="text" required id="initPwd" name="initPwd"  class="layui-input" value="DF123456" style="border: none" >
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">商户ID:</label>
      <div class="layui-input-block">
        <input type="text" required id="merchantId" name="merchantId"  class="layui-input"  style="border: none" >
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">商户秘钥:</label>
      <div class="layui-input-block">
        <textarea type="text" required id="mchPrvKey" name="mchPrvKey"  class="layui-textarea"   ></textarea>
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">回调ip:</label>
      <div class="layui-input-block">
        <input type="text" required id="notifyIp" name="notifyIp"  class="layui-input" value="150.109.63.144" style="border: none;color: red" >
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">对接文档:</label>
      <div class="layui-input-block">
        <input type="text" required id="apiWord" name="apiWord"  class="layui-input" value="http://150.109.63.144:3502/mch/src/views/dev/pay_doc/agpay.html" style="border: none;color: dodgerblue" >
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">支付网关:</label>
      <div class="layui-input-block">
        <input type="text" required id="apiGateway" name="apiGateway"  class="layui-input" value="http://150.109.63.144:3503" style="border: none;color: dodgerblue" >
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">代付下单:</label>
      <div class="layui-input-block">
        <input name="apiSummiturl" id="apiSummiturl"  class="layui-input" value="http://150.109.63.144:3503/api/df/apply" style="border: none;color: dodgerblue">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">代付查询:</label>
      <div class="layui-input-block">
        <input name="apiQueryurl" id="apiQueryurl"  class="layui-input" value="http://150.109.63.144:3503/api/df/queryOrder" style="border: none;color: dodgerblue">
      </div>
    </div>
    <div class="layui-form-item layui-form-text">
      <label class="layui-form-label">余额查询:</label>
      <div class="layui-input-block">
        <input name="apiBalanceurl" id="apiBalanceurl"  class="layui-input" value="http://150.109.63.144:3503/api/df/queryBalance" style="border: none;color: dodgerblue">
      </div>
    </div>
    <p ><STRONG> 系统说明: 为了账户安全，登录成功后请先修改密码，绑定谷歌验证码</STRONG></p>
    <input style="display: block; margin: 50px auto" type="button" class="layui-btn" id="copyBtn" value="复制私钥"/>
    <!--      <button id="copyAll" class="js-clipboard" data-clipboard-text="任意文本">点击复制</button>-->
  </form>
</div>


<script>
  layui.use(['admin', 'table', 'util'], function(){
    var $ = layui.$
            ,admin = layui.admin
            ,table = layui.table
            ,element = layui.element
            ,form = layui.form;


    $("#copyBtn").click(function () {
      var Url2 = document.getElementById("mchPrvKey");
      Url2.select(); // 选择对象
      document.execCommand("Copy"); // 执行浏览器复制命令
      layer.msg("已复制");
    });




    $.getMchInfo = function(mchId) {
      admin.req({
        type: 'get',
        url:  layui.setter.baseUrl + '/mch_info/get' //模拟基本信息接口,
        ,data: {
          access_token : layui.data(layui.setter.tableName).access_token,
          mchId : mchId
        }
        ,error: function(err){
          console.log(err)
        },
        success: function(res){
          if(res.code == 0){
            var privateKey = res.data.privateKey;
            if(privateKey != null && privateKey.length > 0) {
              $('#mchPrvKey').val(res.data.privateKey);
            }
            form.render('radio', 'duijieDivForm');
          }
        }
      });
    };


    // 获取日切信息
    admin.req({
      type: 'post',
      url: layui.setter.baseUrl + '/config/common/getCutOff',
      error: function(err){
        layer.alert(err);
      },
      success: function(res){
        if(res.code == 0){
          $("input:radio[name=cutoffStatus][value="+ res.data+"]").attr("checked", "true");
          form.render('radio');
        }
      }
    });


    element.render('breadcrumb', 'breadcrumb');
    //重点在这里， 获取后台数据， 再拼装， 最后记得form.render


    $("input[name='status'][value='"+1+"']").attr("checked",true);


    $.setCountResult = function(mchId,mchName,status) {
        admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/account/mchCount',
            data: {
              mchId : mchId,
              mchName : mchName,
              status : status
            },
            error: function(err){
                layer.alert(JSON.stringify(err.field), {
                    title: '错误提示'
                })
            },
            success: function(res){
                if(res.code == 0){
                    $('#totalAgnetBalacne').html(res.data.totalAgnetBalacne/100.00);
                }
            }
        });
    };
// 初始化统计结果
    $.setCountResult();

    var tplStatus = function(d){
      var checkedHtml = " mchId='"+d.mchId+"' ";
      if(d.status == 1) {
        checkedHtml += " checked";
      }
      return '<input type="checkbox" lay-filter="statusSwitch" lay-skin="switch" '+checkedHtml+' lay-text="启用|停用">';
    };



    var tplAmount = function(d){
      if(d.agentpayBalance==0){
        return "<span style='color: darkgreen'>" + 0 + "</span>";
      }else {
        return "<span style='color: darkgreen'>" + d.agentpayBalance/100 + "</span>";
      }

    };

    var tplUnbalance = function(d){
      return "<span>" + d.unBalance/100 + "</span>";
    };

    var tplEdit = function(d){
      return "<a  href="+ d.loginMchUrl +" class='layui-btn layui-btn-primary layui-btn-xs' target='_blank'>登录系统</a>" +
              // "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='merchantDetail'>查看信息</a>" +
              // "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='settConfig'>结算设置</a>" +
              // "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='payPassage'>支付通道</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='merchantDuijie'>对接信息</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='agentpayPassage'>代付通道</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='change'>余额变更</a>" +
              "<a class='layui-btn layui-btn-primary layui-btn-xs' lay-event='pwdReset'>重置密码</a>" +
              "<a class='layui-btn layui-btn-xs' lay-event='edit'>编辑</a>";
    };

    //商户列表
    table.render({
      elem: '#XxPay_Mgr_Merchant_dataAll'
      ,url: layui.setter.baseUrl + '/mch_info/list' //列表接口
      ,where: {
          access_token: layui.data(layui.setter.tableName).access_token
      }
      ,id: 'tableReload'
      ,page: true
      ,cols: [[
        {type: 'checkbox', fixed: 'left'}
        ,{field: 'mchId', width: 130, title: '商户ID'}
        ,{field: 'name', width: 180, title: '商户名称'}
        ,{field: 'agentId', width: 90, title: '代理商ID'}
        // ,{field: 'balance', title: '账户余额', width: 100, templet: tplAmount}
        ,{field: 'agentpayBalance', title: '代付账户余额', width: 150, templet: tplAmount}
        ,{field: 'unAgentpayBalance', title: '不可用代付余额', width: 140, templet: '<div class="color: darkred">{{ d.unAgentpayBalance/100 }}</div>'}
        ,{field: 'status',width: 100, title: '状态', templet: tplStatus}
        // ,{field: 'frozenMoney', title: '冻结金额',width: 150, templet: '<div class="color: darkred">{{ d.frozenMoney/100 }}</div>'}
        ,{field: 'createTime', title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
        ,{field: 'edit', title: '操作', width: 415, align: 'center', templet: tplEdit }
      ]]
      ,skin: 'line'
    });

    //监听工具条
    table.on('tool(XxPay_Mgr_Merchant_dataAll)', function(obj){
      var data = obj.data;
      if(obj.event === 'merchantDetail'){
        location.href = layui.setter.baseLocal + "merchant/list/mch_view/mchId=" + data.mchId;
      } else if(obj.event === 'accountDetail'){
        location.href = layui.setter.baseLocal + "merchant/list/account_view/mchId=" + data.mchId;
      } else if(obj.event === 'payPassage'){
        if(data.type == 2) {
          layer.msg('私有账户,无需设置!');
          return;
        }
        location.href = layui.setter.baseLocal + "merchant/pay_passage/list/mchId=" + data.mchId;
      } else if(obj.event === 'agentpayPassage'){
        if(data.type == 2) {
          layer.msg('私有账户,无需设置!');
          return;
        }
        location.href = layui.setter.baseLocal + "merchant/agentpay_passage/list/mchId=" + data.mchId;
      } else if(obj.event === 'settConfig'){
        if(data.type == 2) {
          layer.msg('私有账户,无需设置!');
          return;
        }
        location.href = layui.setter.baseLocal + "merchant/list/mch_sett/mchId=" + data.mchId;
      }else if(obj.event === 'pwdReset'){
        layer.prompt({
          formType: 1,
          title: '请输入新密码'
        }, function(value, index, elem){
          admin.req({
            type: 'get',
            url: layui.setter.baseUrl + '/mch_info/pwd_reset',
            data: {
              mchId : data.mchId,
              password : value
            },
            error: function(err){
              layer.alert(JSON.stringify(err.field), {
                title: '错误提示'
              })
            },
            success: function(res){
              if(res.code == 0){
                layer.msg('修改成功', {icon: 1});
              }
            }
          });
          layer.close(index);
        });
      }else if(obj.event === 'change'){
        location.href = layui.setter.baseLocal + "merchant/list/mch_change/mchId=" + data.mchId;
      }else if(obj.event === 'edit'){
        location.href = layui.setter.baseLocal + "merchant/list/mch_edit/mchId=" + data.mchId;
      }else if(obj.event === 'merchantDuijie'){
        $('#merchantId').val(data.mchId);
        $('#loginAccount').val(data.userName);
        $.getMchInfo(data.mchId);
        //打开子类iframe
        layui.layer.open({
          type: 1,//弹出层类型
          title: '对接信息', //ifrem的标题
          area:['600px','700px'],
          content: $("#duijie"),
          shade: 0,
          closeBtn:1
        })
      }

    });


    $("#batchCutOff").off().on("click", function(){
      var load= layer.open({
        type:1,
        area:['400px','300px'],
        title: '一键日切',
        content: $("#cutofftbl"),
        shade: 0,
        btn: ['确认', '取消'],
        btn1: function(index, layero){
          const data = {};
          data["cutoffStatus"] = $('input[type=radio][name=cutoffStatus]:checked').val();
          admin.req({
            type: 'post',
            url: layui.setter.baseUrl + '/config/common/cutoff',
            data: data,
            error: function(err){
              layer.close(load);
              layer.alert(err);
            },
            success: function(res){
              layer.close(load);
              if(res.code == 0 ) {
                layer.alert("日切成功！",function(layid){
                  parent.layer.close(layid);
                });
              }
            }
          });
        },
        cancel: function(layero,index){
          layer.closeAll();
        }
      });
    });



    $("#resetMchAccount").off().on("click", function(){
      var merchantIds = [];
      var errorMsg = "";
      $.each(table.cache.tableReload, function(){
        var thisObject = $(".layui-table tr[data-index='"+this.LAY_TABLE_INDEX+"'] input[name='layTableCheckbox']");
        if(thisObject.is(':checked')){ //勾选状态
          merchantIds.push(this.mchId);
        }
      });
      if(errorMsg) return layer.alert(errorMsg);
      if(merchantIds.length <= 0) return layer.alert("请勾选需要设置的商户！");
      var load= layer.open({
        type:1,
        area:['500px','600px'],
        title: '一键清零'
        ,content: $("#resetbut"),
        shade: 0,
        btn: ['提交']
        ,btn1: function(index, layero){
          var superPassword=$.trim($('#superpassword').val());
          if(superPassword == '' ) {
            layer.alert("请输入密码",{title: '提示'});
            return false;
          }
          layer.prompt({
            formType: 0,
            title: '请输入谷歌验证码'
          }, function (value, index, elem) {
            admin.req({
              url: layui.setter.baseUrl + '/inner/google_auth' //校验谷歌验证码
              , data: {
                googleCode: value
              }
              , success: function (res1) {
                if (res1.code == 0) {
                  var data = {};
                  data["password"] = superpassword;
                  data["merchantIds"] = JSON.stringify(merchantIds);
                  admin.req({
                    type: 'post',
                    url: layui.setter.baseUrl + '/mch_pay_passage/batchUpdate',
                    data: data,
                    // data: {merchantIds : JSON.stringify(merchantIds)},
                    error: function(err){
                      layer.close(load);
                      layer.alert(err);
                    },
                    success: function(res){
                      layer.close(load);
                      if(res.code == 0 ) {
                        layer.alert("切换成功！",function(layid){
                          parent.layer.close(layid);
                          table.reload('tableReload');
                        });
                      }
                    }
                  });
                }
                layer.close(index);
              }
            });
          });
        },
        cancel: function(layero,index){
          layer.closeAll();
        }
      });
    });

    form.on('switch(statusSwitch)', function(data){

      var mchId = $(data.elem).attr('mchId');
      var updateState = data.elem.checked ? "1" : "0";
      var loadingIndex = layer.load();
      admin.req({
        type: "POST",
        url: layui.setter.baseUrl + '/mch_info/updateStatus',
        data: {mchId: mchId, status: updateState},
        success: function(res){
          if(res.code == 0) {
            table.reload('tableReload');
          }
        },
        complete:function(){
          layer.close(loadingIndex);
        }
      });
    });

    // 搜索
    var $ = layui.$, active = {
      reload: function(){
        var mchId = $('#mchId').val();
        var name = $('#name').val();
        var status = $('#status').val();
        $.setCountResult(mchId,name,status);
        //执行重载
        table.reload('tableReload', {
          page: {
            curr: 1 //重新从第 1 页开始
          }
          ,where: {
            mchId: mchId,
            name:name,
            status:status
          }
        });
      }
    };
    $('#search').on('click', function() {
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });

    // 渲染表单
    form.render();
  });
</script>